package com.fzh.netty;

import java.net.InetSocketAddress;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

/**
 * 应答程序的客户端
 * 
 * @author ZoharFang
 * @date 2016年8月31日
 */
public class EchoClient {

	private final String host;

	private final int port;

	public EchoClient(String host, int port) {
		this.host = host;
		this.port = port;
	}

	public void start() throws Exception {
		/**
		 * 创建EventLoopGroup对象并设置到Bootstrap中，EventLoopGroup可以理解为是一个线程池，
		 * 这个线程池用来处理连接、接受数据、发送数据
		 */
		EventLoopGroup group = new NioEventLoopGroup();
		try {
			//创建Bootstrap对象用来引导启动客户端
			Bootstrap b = new Bootstrap();
			b.group(group).channel(NioSocketChannel.class).remoteAddress(
					new InetSocketAddress(host, port))	//设置InetSocketAddress，指定连接的服务器地址
			        .handler(new ChannelInitializer<SocketChannel>() {

						@Override
						protected void initChannel(SocketChannel ch) throws Exception {
							ch.pipeline().addLast(new StringEncoder())	//编码器将Java对象转成字节码
							.addLast(new StringDecoder())	//解码器将消息从字节码转成Java对象
							.addLast(new EchoClientHandler());//添加一个ChannelHandler，客户端成功连接服务器后就会被执行
						}
					});
			ChannelFuture f = b.connect().sync();	//连接服务器
			f.channel().closeFuture().sync();
		} finally {
			group.shutdownGracefully().sync();	//关闭EventLoopGroup来释放资源
		}
	}
	
	public static void main(String[] args) throws Exception {
		new EchoClient("127.0.0.1",20000).start();
	}
	
}
